<template>
  <div class="home">
    <!-- 全屏轮播Banner -->
    <div class="banner">
      <el-carousel
        height="100vh"
        :interval="5000"
        arrow="hover"
        indicator-position="none"
      >
        <el-carousel-item v-for="(item, index) in bannerItems" :key="index">
          <div
            class="banner-slide"
            :style="{
              backgroundImage: item.imageUrl
                ? `url(${getImageUrl(item.imageUrl)})`
                : '',
            }"
          >
            <div class="banner-overlay">
              <div class="banner-content container">
                <h1 class="fade-in-up">{{ item.title }}</h1>
                <p class="fade-in-up">{{ item.subtitle }}</p>
                <div class="banner-actions fade-in-up">
                  <el-button
                    type="primary"
                    size="large"
                    @click="$router.push('/customize')"
                  >
                    立即定制
                    <el-icon class="el-icon--right"><ArrowRight /></el-icon>
                  </el-button>
                  <el-button
                    size="large"
                    @click="$router.push('/destinations')"
                  >
                    浏览目的地
                    <el-icon class="el-icon--right"><Location /></el-icon>
                  </el-button>
                  <el-button
                    v-if="isLoggedIn"
                    size="large"
                    @click="$router.push('/consult')"
                  >
                    私人咨询
                    <el-icon class="el-icon--right"><ArrowRight /></el-icon>
                  </el-button>
                  <el-button
                    v-if="isLoggedIn"
                    size="large"
                    @click="$router.push('/routes')"
                  >
                    旅游攻略
                    <el-icon class="el-icon--right"><ArrowRight /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 服务特色板块 -->
    <div class="services-section">
      <div class="container">
        <h2 class="section-title">我们的服务</h2>
        <div class="services-grid">
          <div
            v-for="(service, index) in services"
            :key="index"
            class="service-card"
            :class="{ 'fade-in': true }"
          >
            <div class="service-content">
              <div
                class="service-icon"
                :style="{
                  background: `linear-gradient(135deg, ${service.color.primary}, ${service.color.secondary})`,
                  boxShadow: `0 8px 16px ${service.color.primary}33`,
                }"
              >
                <el-icon :size="28">
                  <component :is="service.icon" />
                </el-icon>
              </div>
              <h3>{{ service.desc }}</h3>
              <div
                class="service-line"
                :style="{ background: service.color.primary }"
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 热门目的地 -->
    <div class="destinations-section">
      <div class="container">
        <div class="section-header">
          <h2 class="section-title">热门目的地</h2>
          <el-button type="primary" link @click="$router.push('/destinations')">
            查看更多 <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        <div class="destinations-grid">
          <div
            v-for="dest in destinations"
            :key="dest.id"
            class="destination-card hover-effect"
            @click="viewDestination(dest.id)"
          >
            <div class="card-image">
              <img :src="getImageUrl(dest.imageUrl)" :alt="dest.name" />
              <div class="image-overlay">
                <div class="dest-badges">
                  <el-tag
                    v-for="badge in (dest.badges || []).slice(0, 2)"
                    :key="badge"
                    :style="getTagStyle(badge)"
                    size="small"
                  >
                    {{ badge }}
                  </el-tag>
                </div>
              </div>
            </div>
            <div class="card-content">
              <h3>{{ dest.name }}</h3>
              <p>{{ dest.subtitle }}</p>
              <div class="card-meta">
                <div class="meta-item">
                  <el-icon><Location /></el-icon>
                  <span>{{ dest.region }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Star /></el-icon>
                  <span>{{ dest.rating }}分</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 定制流程 -->
    <div class="process-section">
      <div class="container">
        <h2 class="section-title">定制流程</h2>
        <div class="process-grid">
          <div
            v-for="(step, index) in processSteps"
            :key="index"
            class="process-card"
          >
            <div class="step-number">{{ index + 1 }}</div>
            <p>{{ step.desc }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 旅行故事 -->
    <div class="stories-section">
      <div class="container">
        <div class="section-header">
          <h2 class="section-title">精彩游记</h2>
          <el-button type="primary" link @click="$router.push('/stories')">
            更多故事 <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        <div class="stories-grid">
          <div
            v-for="story in stories"
            :key="story.id"
            class="story-card hover-effect"
            @click="viewStory(story.id)"
          >
            <div class="story-image">
              <img :src="getImageUrl(story.coverImage)" :alt="story.title" />
              <span class="story-category">{{ story.category }}</span>
            </div>
            <div class="story-content">
              <h3>{{ story.title }}</h3>
              <p>{{ story.excerpt }}</p>
              <div class="story-meta">
                <div class="author">
                  <img
                    :src="getImageUrl(story.authorAvatar)"
                    :alt="story.authorName"
                  />
                  <span>{{ story.authorName }}</span>
                </div>
                <time>{{ story.publishDate }}</time>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 修改导入语句
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { Star, Location, ArrowRight } from "@element-plus/icons-vue";
import { getImageUrl } from "@/utils/format";
import { getBanners, getHotDestinations, getLatestStories } from "@/api/home";
import { ElLoading, ElMessage } from "element-plus";

const router = useRouter();

// 初始化数据
const bannerItems = ref([]);
const destinations = ref([]);
const stories = ref([]);

// 服务特色数据
const services = [
  {
    icon: "Guide",
    title: "专业规划",
    desc: "资深顾问定制专属行程",
    color: {
      primary: "#2F54EB",
      secondary: "#ADC6FF",
    },
  },
  {
    icon: "HomeFilled",
    title: "品质保障",
    desc: "精选优质住宿与用车",
    color: {
      primary: "#13C2C2",
      secondary: "#87E8DE",
    },
  },
  {
    icon: "Avatar",
    title: "专业导游",
    desc: "持证导游全程陪同",
    color: {
      primary: "#722ED1",
      secondary: "#D3ADF7",
    },
  },
  {
    icon: "Service",
    title: "贴心服务",
    desc: "24小时在线咨询",
    color: {
      primary: "#F5222D",
      secondary: "#FFA39E",
    },
  },
];

// 定制流程数据
const processSteps = [
  {
    icon: "ChatLineSquare",
    title: "在线咨询",
    desc: "提交您的旅行需求，专业顾问会第一时间与您联系",
  },
  {
    icon: "Edit",
    title: "方案定制",
    desc: "根据您的偏好，为您量身打造专属旅行方案",
  },
  {
    icon: "Calendar",
    title: "行程确认",
    desc: "确认行程细节，选择心仪的出行日期",
  },
  {
    icon: "Promotion",
    title: "开启旅程",
    desc: "享受专业导游带队，尽情探索汉中美景",
  },
];

// 获取首页数据
const fetchHomeData = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "加载中...",
    background: "rgba(255, 255, 255, 0.7)",
  });

  try {
    const [bannersRes, destinationsRes, storiesRes] = await Promise.all([
      getBanners({ size: 3 }), // 获取轮播图数据
      getHotDestinations({ size: 3 }), // 获取热门目的地数据
      getLatestStories({ limit: 3 }), // 获取最新故事数据
    ]);
    
    // 处理 banner 数据
    if (bannersRes.code === 200) {
      bannerItems.value = bannersRes.data || [];
    } else {
      console.error("获取Banner数据失败:", bannersRes.message);
      // 设置默认数据
      bannerItems.value = [
        {
          title: "探索汉中秘境",
          subtitle: "让我们为您定制专属旅行体验",
        }
      ];
    }

    // 处理目的地数据
    if (destinationsRes.code === 200) {
      const destData = destinationsRes.data;
      destinations.value = Array.isArray(destData)
        ? destData.slice(0, 3) // 确保只显示3个
        : (destData && destData.list ? destData.list.slice(0, 3) : []);
      
      // 确保数据格式正确
      destinations.value = destinations.value.map(dest => ({
        id: dest.id,
        name: dest.name,
        subtitle: dest.description || dest.subtitle || '',
        imageUrl: dest.coverImages && dest.coverImages.length > 0 
          ? dest.coverImages[0] 
          : (dest.imageUrl || ''),
        region: dest.region || '汉中',
        rating: dest.rating || 4.5,
        badges: Array.isArray(dest.badges) ? dest.badges : (dest.badges ? dest.badges.split(',') : [])
      }));
    } else {
      console.error("获取目的地数据失败:", destinationsRes.message);
    }

    // 处理故事数据
    if (storiesRes.code === 200) {
      const storyData = storiesRes.data;
      stories.value = Array.isArray(storyData)
        ? storyData.slice(0, 3)
        : (storyData && storyData.list ? storyData.list.slice(0, 3) : []);
      
      // 确保数据格式正确
      stories.value = stories.value.map(story => ({
        id: story.id,
        title: story.title,
        excerpt: story.excerpt || story.summary || '',
        coverImage: story.coverImage || '',
        category: story.category || '旅行攻略',
        authorName: story.authorName || (story.author ? story.author.name : '旅行者'),
        authorAvatar: story.authorAvatar || (story.author ? story.author.avatar : ''),
        publishDate: story.publishDate || story.createTime || '2023-01-01'
      }));
    } else {
      console.error("获取故事数据失败:", storiesRes.message);
    }
  } catch (error) {
    console.error("获取首页数据失败:", error);
    ElMessage.error("获取数据失败，请稍后重试");
    
    // 设置默认数据，确保页面不会空白
    if (bannerItems.value.length === 0) {
      bannerItems.value = [
        {
          title: "探索汉中秘境",
          subtitle: "让我们为您定制专属旅行体验",
          
        }
      ];
    }
  } finally {
    loading.close();
  }
};

// 优化目的地查看
const viewDestination = (id) => {
  router.push(`/destination/${id}`);
};

// 优化故事查看
const viewStory = (id) => {
  router.push(`/story/${id}`);
};

// 添加标签样式函数
const getTagStyle = (badge) => {
  const styles = {
    摄影创作: { bg: "#e6fffb", text: "#13c2c2" },
    自然风光: { bg: "#f6ffed", text: "#52c41a" },
    人文古迹: { bg: "#fff0f6", text: "#eb2f96" },
    美食探索: { bg: "#fff7e6", text: "#fa8c16" },
  };
  const style = styles[badge] || { bg: "#f5f5f5", text: "#666666" };
  return {
    backgroundColor: style.bg,
    color: style.text,
    border: "none",
  };
};

const isLoggedIn = computed(() => !!localStorage.getItem('token'));

onMounted(() => {
  fetchHomeData();
});
</script>

<style scoped>
.banner {
  position: relative;
  height: 100vh;
}

.banner-slide {
  height: 100%;
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

.banner-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0.3) 0%,
    rgba(0, 0, 0, 0.5) 100%
  );
  display: flex;
  align-items: center;
}

.banner-content {
  color: white;
  text-align: center;
}

.banner-content h1 {
  font-size: 4rem;
  font-weight: 700;
  margin-bottom: 20px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.banner-content p {
  font-size: 1.5rem;
  margin-bottom: 40px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.banner-actions {
  display: flex;
  gap: 20px;
  justify-content: center;
}

/* 服务特色样式 */
.services-section {
  padding: 40px 0; /* 从80px减少到40px */
}

.services-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px; /* 从30px减少到20px */
  margin-top: 30px; /* 从50px减少到30px */
}

.service-card {
  text-align: center;
  padding: 25px 15px; /* 从40px 20px减少到25px 15px */
  border-radius: 16px;
  background: white;
  transition: all 0.3s ease;
  border: 1px solid rgba(0, 0, 0, 0.06);
}

.service-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.08);
}

.service-icon {
  width: 64px;
  height: 64px;
  margin: 0 auto 15px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  transition: all 0.3s ease;
}

.service-card:hover .service-icon {
  transform: translateY(-5px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.15);
}

.service-content {
  position: relative;
  z-index: 1;
}

.service-content h3 {
  font-size: 1.1rem; /* 稍微调小标题字号 */
  margin: 15px 0 10px;
  color: var(--text-color);
  font-weight: 600;
}

.service-line {
  width: 30px; /* 减小分隔线宽度 */
  height: 2px; /* 减小分隔线高度 */
  background: linear-gradient(
    90deg,
    var(--primary-color),
    transparent
  ); /* 添加渐变效果 */
  margin: 10px auto 0;
  opacity: 0.8;
}

/* 目的地板块样式 */
.destinations-section {
  padding: 40px 0; /* 从80px减少到40px */
  background: var(--light-bg);
}

.destinations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px; /* 从30px减少到20px */
  margin-top: 20px; /* 从40px减少到30px */
}

.destination-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.card-image {
  position: relative;
  height: 200px; /* 从240px减少到200px */
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.destination-card:hover .card-image img {
  transform: scale(1.1);
}

.image-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0.2),
    rgba(0, 0, 0, 0.6)
  );
  opacity: 0;
  transition: opacity 0.3s ease;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.destination-card:hover .image-overlay {
  opacity: 1;
}

.card-content {
  padding: 15px; /* 从20px减少到15px */
}

.card-content h3 {
  font-size: 1.4rem;
  margin: 0 0 10px;
  color: var(--text-color);
}

.card-content p {
  color: var(--text-color-secondary);
  margin-bottom: 15px;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  color: var(--text-color-secondary);
}

/* 定制流程样式 */
.process-section {
  padding: 40px 0; /* 从80px减少到40px */
  background: white;
}

.process-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px; /* 从30px减少到20px */
  margin-top: 30px; /* 从50px减少到30px */
}

.process-card {
  text-align: center;
  padding: 20px; /* 从30px减少到20px */
  border-radius: 16px;
  background: var(--light-bg);
  position: relative;
}

.step-number {
  width: 40px;
  height: 40px;
  background: var(--primary-color);
  color: white;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  font-weight: bold;
  margin: 0 auto 20px;
}

/* 故事板块样式 */
.stories-section {
  padding: 40px 0; /* 从80px减少到40px */
  background: var(--light-bg);
}

.stories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 20px; /* 从30px减少到20px */
  margin-top: 20px; /* 从40px减少到30px */
}

.story-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.story-image {
  position: relative;
  height: 180px; /* 从200px减少到180px */
}

.story-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.story-category {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  font-size: 0.9rem;
  color: var (--primary-color);
}

.story-content {
  padding: 15px; /* 从20px减少到15px */
}

.story-content h3 {
  font-size: 1.2rem;
  margin: 0 0 10px;
  color: var(--text-color);
}

.story-content p {
  color: var(--text-color-secondary);
  margin-bottom: 20px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.story-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--text-color-secondary);
  font-size: 0.9rem;
}

.author {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author img {
  width: 30px;
  height: 30px;
  border-radius: 15px;
  object-fit: cover;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .banner-content h1 {
    font-size: 2.5rem;
  }

  .banner-content p {
    font-size: 1.2rem;
  }

  .services-section,
  .destinations-section,
  .process-section,
  .stories-section {
    padding: 30px 0; /* 从40px减少到30px */
  }

  .section-title {
    font-size: 1.5rem; /* 从1.8rem减少到1.5rem */
    margin-bottom: 20px;
  }

  .destinations-grid,
  .stories-grid {
    gap: 15px; /* 在移动端进一步减小间距 */
  }
}

/* 动画效果 */
.fade-in-up {
  opacity: 0;
  transform: translateY(20px);
  animation: fadeInUp 0.6s ease forwards;
}

.fade-in {
  opacity: 0;
  animation: fadeIn 0.6s ease forwards;
}

@keyframes fadeInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  to {
    opacity: 1;
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px; /* 从40px减少到30px */
}

.dest-badges {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>
